<?php
/**
 * 内容页
 * @author
 * @version 1.0
 * create Date 2013-07-22
 */
class ArticleAction extends PublicAction {

	/**
	 * 进入内容列表，这里会得到栏目列表
	 * M2
	 */
    public function contentlist() {
        $this->display();
    }

    public function contentlistdialog() {
    	if($_GET) {
    		$cid=empty($_GET['cid'])? 0 : $_GET['cid'];
    		if(!empty($_GET['cid'])){
    			$map['cid'] = $cid;
    		}
    		if(!empty($_GET['title'])){
    			$map['title'] = array ('like','%' . $_GET['title'] . '%');
    		}
    		$map['siteid'] = $_GET['siteid'];
    		$map['status'] = array('eq',1);
    		$ca = M ( 'cms_article' );
    		import ( "ORG.Util.Page" );
    		$count = $ca->where($map)->count ();
    		$p = new Page ( $count, 10 );
    		$clist = M('cms_article')->where($map)->order('`display_order` DESC,`id` DESC')->limit ( $p->firstRow . ',' . $p->listRows )->select();
    		$page = $p->ajax_show ();
    		$this->assign ( 'page', $page );

    		$this->assign('list',$clist);
            $this->assign('sid', $map['siteid']);
            $this->assign('title', $_GET['title']);
    		$this->getSiteCateBySid($map['siteid'],$cid);
    	}
    	$this->display();
    }

    /**
     * 获取内容列表
     * M2
     */
    public function content() {
        if($_REQUEST) {
            $map['siteid'] = $_REQUEST['sid'];
            $id = intval($_REQUEST['id']);
            if(!empty($id)){
                $map['id'] = $id;
            }
            if (isset($_REQUEST['title']) && !empty($_REQUEST['title'])) {
                $map['title'] = array('like','%'.trim($_REQUEST['title']).'%');
                $this->assign('title', $_REQUEST['title']);
            }
            if (isset($_REQUEST['author']) && !empty($_REQUEST['author'])) {
                $map['author'] = array('like','%'.common('Html')->text(trim($_REQUEST['author'])).'%');
                $this->assign('author', $_REQUEST['author']);
            }
            if (isset($_REQUEST['create_uname']) && !empty($_REQUEST['create_uname'])) {
                $map['create_uname'] = trim($_REQUEST['create_uname']);
            }
            if (isset($_REQUEST['sh']) && ($_REQUEST['sh'] <> '')) {
                $map['status'] = $_REQUEST['sh'];
                $this->assign('sh', $_REQUEST['sh']);
            } else {
                $map['status'] = array('neq',-1);
            }
            if (isset($_REQUEST['selectAll']) && ($_REQUEST['selectAll'] === 'all')) {
                $this->assign('selectAll', $_REQUEST['selectAll']);
            } else {
                $map['cid'] = empty($_REQUEST['cid'])? 0 : $_REQUEST['cid'];
                session('cid', $map['cid']);
            }
            if (isset($_REQUEST['relatednode']) && ($_REQUEST['relatednode'] === 'true')) {
            	$this->assign('relatednode', $_REQUEST['relatednode']);
            	$map['related_node_list']=array('neq','');
            }

            $ca = M ( 'cms_article' );
            import ( "ORG.Util.Page" );
            $count = $ca->where($map)->count ();
            $p = new Page ( $count, 20, http_build_query($_POST));
            $clist = M('cms_article')->where($map)->order('`display_order` DESC,`id` DESC')->limit ( $p->firstRow . ',' . $p->listRows )->select();
            $p->parameter .= "&sid=".$_REQUEST['sid']."&cid=".$_REQUEST['cid']."&title=".$_REQUEST['title']."&sh=".$_REQUEST['sh']."&status=".$_REQUEST['status']."&selectAll=".$_REQUEST['selectAll'];
            $page = $p->show ();
            $param = array();
            $param['sid'] = $_REQUEST['sid'];
            $param['cid'] = $_REQUEST['cid'];
            !empty($_REQUEST['title']) && $param['title'] = $_REQUEST['title'];
            !empty($_REQUEST['sh']) && $param['sh'] = $_REQUEST['sh'];
            !empty($_REQUEST['status']) && $param['status'] = $_REQUEST['status'];
            !empty($_REQUEST['selectAll']) && $param['selectAll'] = $_REQUEST['selectAll'];
            !empty($_REQUEST['author']) && $param['author'] = $_REQUEST['author'];
            !empty($_REQUEST['create_uname']) && $param['create_uname'] = $_REQUEST['create_uname'];
            !empty($_REQUEST['relatednode']) && $param['relatednode'] = $_REQUEST['relatednode'];
            !empty($_REQUEST['id']) && $param['id'] = $_REQUEST['id'];
            !empty($_REQUEST['p']) && $param['p'] = $_REQUEST['p'];
//            $param = array(
//                'sid'=>,
//                'cid'=>$_REQUEST['cid'],
//                'title'=>$_REQUEST['title'],
//                'sh'=>$_REQUEST['sh'],
//                'status'=>$_REQUEST['status'],
//                'selectAll'=>$_REQUEST['selectAll']
//            );
            $jumpUrl = urlencode(URL('cms/Article/content',$param));
            $this->assign('jumpUrl',$jumpUrl);
            $this->assign ( 'page', $page );
            foreach ($clist as $k => $v){
            	//得到站点信息
            	if (($sited = S('cache_siteid_'.$v['siteid'])) === false) {
            		$sited = M('cms_site')->where('siteid='.$v['siteid'])->find();
            		S('cache_siteid_'.$v['siteid'], $sited);
            	}
            	$curdomain=$sited['domain'];
            	$clist[$k]['imageurl'] = $this->getRealImageUrl($curdomain,$clist[$k]['imageurl']);

            	//得到内容生成链接
            	if($clist[$k]['status']=="1"){
	            	if(empty($clist[$k]['url'])){
	            		// 获取站点目录
	            		$dirname = $sited['dirname'];
	            		// 获取内容的命名规则
	            		if ($category_list = S('cache_channel_'.$clist[$k]['cid']) === false) {
	            			$category_list = M('cms_category')->where('id='.$clist[$k]['cid'])->find();
	            			S('cache_channel_'.$clist[$k]['cid'], $category_list);
	            		}
	            		$artnaming = $category_list['artnaming'];
	            		if (empty($artnaming)) {
	            			$changeStyle = model('Data')->get('cmsconfig:site-'.$clist[$k]['siteid']);
	            			$artnaming = $changeStyle['artnaming'];
	            		}
	            		$artnaming = str_replace('{@ChannelID}', $clist[$k]['cid'], $artnaming);
	            		$artnaming = str_replace('{@ContentID}', $clist[$k]['id'], $artnaming);
	            		$artnaming = str_replace('{@Year}', date("Y"), $artnaming);
	            		$artnaming = str_replace('{cateid}', $clist[$k]['cid'], $artnaming);
	            		$artnaming = str_replace('{contentid}', $clist[$k]['id'], $artnaming);
	            		$clist[$k]['contenturl']=$dirname . '/'. $artnaming;
//                                //判断链接是否有效（是否已经生成了内容页）
//                                if(file_get_contents($clist[$k]['contenturl'])){
//                                    $clist[$k]['page_created'] = 1;
//                                }
	            	}else{
	            		$clist[$k]['contenturl']=$clist[$k]['url'];
	            	}
            	}else{
            		$clist[$k]['contenturl']=URL('cms/Article/addcontent',array('id'=>$clist[$k]['id'],'type'=>$clist[$k]['classid'],'sid'=>$v['siteid']));
            	}
            }
            $this->assign('list',$clist);
            $this->assign('cid', session('cid'));
        }
        if(!empty($_GET['site_name'])) {
            $sid = $this->getSiteId($_GET['site_name']);
        } else {
            $sid = intval($_REQUEST['sid']);
        }
        $this->assign('sid',$sid);
        if(($mlist = S('modellist'.$sid)) === false){
            $modellist = M('cms_class') -> where("`status`=1")->select();
            S('modellist'.$sid,$modellist);
            $mlist = $modellist;
        }
        $this->assign('modellist',$mlist);
        $this->display();
    }
    
    /**
     * 获取删除内容列表
     * M2
     */
    public function deletecontentlist() {
    	if($_GET) {
    		$cid=empty($_GET['cid'])? 0 : $_GET['cid'];
    		$this->getSiteCate($cid);
    		if(!empty($_GET['cid'])){
    			$map['cid'] = $cid;
    		}
    		if(!empty($_GET['title'])){
    			$map['title'] = array ('like','%' . $_GET['title'] . '%');
    		}
    		$map['status'] = array('eq',-1);
    		$ca = M ( 'cms_article' );
    		import ( "ORG.Util.Page" );
    		$count = $ca->where($map)->count ();
    		$p = new Page ( $count, 20 );
    		$clist = M('cms_article')->where($map)->order('`display_order` DESC,`id` DESC')->limit ( $p->firstRow . ',' . $p->listRows )->select();
    		$page = $p->show ();
    		$this->assign ( 'page', $page );

    		foreach ($clist as $k => $v){
    			//得到站点信息
    			if (($sited = S('cache_siteid_'.$v['siteid'])) === false) {
    				$sited = M('cms_site')->where('siteid='.$v['siteid'])->find();
    				S('cache_siteid_'.$v['siteid'], $sited);
    			}
    			$curdomain=$sited['domain'];
    			$clist[$k]['imageurl'] = $this->getRealImageUrl($curdomain,$clist[$k]['imageurl']);
    		}
    		$this->assign('list',$clist);
    		$this->assign('title',$_GET['title']);
    		$this->assign('cid',$cid);
    	}
    	$this->display();
    }

    /**
     * 获取内容信息
     * M2
     */
    public function getContentInfo() {
        $map['id'] = $_POST['id'];
        $clist = M('cms_article')->where($map)->order('`display_order` DESC,`id` DESC')->select();
        echo json_encode($clist);
    }

    /**
     * 内容排序
     */
    public function display_order() {
        display_order('cms_article');
    }

    /**
     * 添加或修改内容
     */
    public function addcontent(){
        if(!empty($_GET['id'])){
            $data['id'] = $_GET['id'];
            $res = M('cms_article') -> where($data) -> find();
            $articlegroup = explode(",",$res['group_name_collection']);
            $isindexnews = explode(",",$res['is_index_news']);
            $this->assign("articlegroup",$articlegroup);
            $this->assign("isindexnews",$isindexnews);
            $relate_articles_arr = M('cms_relatedarticle') ->field('rid,rtitle,rcid') -> where($data) -> select();
            $relate_articles = array();
            foreach ($relate_articles_arr as $k => $v){
            	$relate_articles[] = $v['rid'].'_yl_'.$v['rtitle'].'_yl_'.$v['rcid'];
            }
            if(!empty($relate_articles)){
            	$this->assign("related_articles_div",$relate_articles);
            }

            $list = D('Block')->reBlockListByContentID($data['id']);
            if ($list) {
                $this->assign('block_articles_div', $list);
            }

            //改变编辑器中的图片路径
            if (($sited = S('cache_siteid_'.$res['siteid'])) === false) {
            	$sited = M('cms_site')->where('siteid='.$res['siteid'])->find();
            	S('cache_siteid_'.$res['siteid'], $sited);
            }
            $res['content'] = str_replace("@/",$sited['domain']."/", htmlspecialchars_decode($res['content']));
            $res['weight'] = intval($res['weight']);
            $res['imageurl'] = $this->getRealImageUrl($sited['domain'],$res['imageurl']);
            $res['big_imageurl'] = $this->getRealImageUrl($sited['domain'],$res['big_imageurl']);

            if($res['classid']==="3"){
            	$pictures = D('Picture') -> where("`articleid`=".$res['id']) ->order("id")-> select();
            	$this->assign("pictures",$pictures);
            }
            $this->assign('callback', $_GET['callback']);
            $this->getSiteCateBySid($res['siteid'],$res['cid']);
        } else {
            $res['cid'] = $_GET['cid'];
            $res['author'] = common('String')->getUserName($this->mid);
            $res['classid'] = $_GET['classId'];
        	$res['siteid'] = $_GET['sid'];
        	$this->getSiteCateBySid($res['siteid'],$_GET['cid']);
        }
        $this->assign('res',$res);
        $grouplist = D('Group') -> getGroupList($res['siteid'],"1");
        $this->assign('grouplist',$grouplist);

        $this->assign('pagesource',$_GET['source']);

        $type = $_GET['type'];
        $displayFile = "addcontent";
        if($type == "pic" || $type == "3"){
            $displayFile = "addpic_content";
        } else if ($type == "video" || $type == "2"){
            $displayFile = "addvideo_content";
        }
        $this->display($displayFile);
    }

    /**
     * 文件上传动作
     */
    public function uploadFile(){
        $sid = intval($_GET['sid']);
        $cmsconfig = model('Data')->get('cmsconfig:site-'.$sid);
        $picSavePath = empty($cmsconfig['picSavePath'])?'./data/cms/upload':$cmsconfig['picSavePath'];
        $picSavePath = substr($picSavePath,2,strlen($picSavePath)).'/';
        $save_path = SITE_PATH.'/'.$picSavePath;
        if (!file_exists($save_path)) {
            mk_dir($save_path);
        }
        uploadPic($save_path,$picSavePath);
    }

    /**
     * 执行添加内容动作
     */
    public function doAddContent(){
        if($_POST){
            $data = $_POST;
            unset($data['pagesource']);
            //多点几次，重复新增
            $listarticle = M('cms_article') -> where("title='".$data['title']."' and cid=".$data['cid']) -> select();
            if(count($listarticle)<=0){
	            $data['group_name_collection'] = empty($data['group_name_collection'])?"":implode(",",$data['group_name_collection']);
	            $data['is_index_news'] = empty($data['is_index_news'])?"":implode(",",$data['is_index_news']);
	            $data['create_uid'] = $this->mid;
	            $data['create_uname'] = common('String')->getUserName($this->mid);
	            $data['update_uid'] = $this->mid;
	            $data['update_uname'] = common('String')->getUserName($this->mid);
	            $data['inputtime'] = time();
	            $data['updatetime'] = time();
	            $data['weight'] = intval($data['weight']);
// 	            $data['related_articles'] = implode(",",$data['related_articles']);
                $data['content'] = htmlspecialchars(stripslashes($data['content']));
                
                $related_articles = $data['related_articles'];
                unset($data['related_articles']);
                
	            $id = M('cms_article') -> add($data);
	            if($id !== false){
					foreach ($related_articles as $k => $v){
						$articles = explode('_yl_', $v);
						$related_articles_arr[$k]['id'] = $id;
						$related_articles_arr[$k]['siteid'] = $data['siteid'];
						$related_articles_arr[$k]['rid'] = $articles[0];
						$related_articles_arr[$k]['rtitle'] = $articles[1];
						$related_articles_arr[$k]['rcid'] = $articles[2];
					}
					if (!empty($related_articles_arr)) {
						M('cms_relatedarticle') -> addAll($related_articles_arr);
					}
	            	
                    if (!empty($data['block_articles'])) {
                        $block_articles = implode(",",$data['block_articles']);
                        $blockId = R('Block/createBlock', array(array($id), $block_articles));
                    }

	            	$sid = intval($_POST['siteid']);
	            	$cmsconfig = model('Data')->get('cmsconfig:site-'.$sid);

	            	if($data['classid'] ==="3"){
	            		$imageurl = $data["imageurl"];
	            		$imagedes = $data["imagedes"];
	            		$nowtime = time();
	            		foreach ($imageurl as $k => $v){
	            			$pictures[$k]["siteid"] = $data["siteid"];
	            			$pictures[$k]["categoryid"] = $data["cid"];
	            			$pictures[$k]["articleid"] = $id;
	            			$pictures[$k]["authorid"] = $this->mid;
	            			$pictures[$k]["author"] = $data["author"];
	            			$pictures[$k]["ctime"] = $nowtime;
	            			$pictures[$k]["utime"] = $nowtime;
	            			$pictures[$k]["imageurl"] = $v;
	            			$pictures[$k]["des"] = $imagedes[$k];
	            		}
	            		D('Picture') -> addAll($pictures);
	            	}
	                M('cms_article') -> where("`id`=$id") ->setField("display_order",$id);
	                M('cms_category') -> where("`id`= {$data['cid']}") -> setInc('content_num');
	                S('catelist'.$sid,NULL);
	                S('articlelist_'.$data['cid'],NULL);
	                if($cmsconfig['createcontent'] == 1){
	                    $this->createContentsPage($id,$data['cid'],$sid);
	                }
	                $this->assign('jumpUrl',URL('cms/Article/content',array('cid'=>intval($_POST['cid']),'sid'=>$sid)));
	                $this->success('操作成功');
	            } else {
	                $this->error('操作失败');
	            }
            } else {
                $this->error('内容标题重复');
            }
        }
    }

    /**
     * 执行修改内容动作
     */
    public function doEditContent(){
        if($_POST){
            $data = $_POST;
            $pagesource=$data['pagesource'];
            unset($data['pagesource']);
            $data['group_name_collection'] = empty($data['group_name_collection'])?"":implode(",",$data['group_name_collection']);
            $data['is_index_news'] = empty($data['is_index_news'])?"":implode(",",$data['is_index_news']);
            $data['update_uid'] = $this->mid;
            $data['update_uname'] = common('String')->getUserName($this->mid);
            $data['updatetime'] = time();
            $data['weight'] = intval($data['weight']);
//             $data['related_articles'] = implode(",",$data['related_articles']);
            $data['content'] = htmlspecialchars(stripslashes($data['content']));
            
            $sid = intval($data['siteid']);
            $cmsconfig = model('Data')->get('cmsconfig:site-'.$sid);
            
            $related_articles = $data['related_articles'];
            unset($data['related_articles']);
            if(empty($data['is_recommend'])){
            	$data['is_recommend']=0;
            }
            if(empty($data['is_hot'])){
            	$data['is_hot']=0;
            }
            if(empty($data['is_color'])){
            	$data['is_color']=0;
            }
            if(empty($data['is_top'])){
            	$data['is_top']=0;
            }
            $result = M('cms_article') -> save($data);
            // add by jepin 20141029
            if($data['cid']!=$data['ocid']){
            	$sqlpuls ="update ".$this->_dbPrefix."cms_category  c set c.content_num =c.content_num +1 where  c.id =".$data['cid'];
            	$sqlde ="update ".$this->_dbPrefix."cms_category  c set c.content_num =c.content_num -1 where  c.id =".$data['ocid'] ;
            	M()->query($sqlpuls);
            	M()->query($sqlde);
            }
            if($result !== false){
            	M('cms_relatedarticle') ->where('id='.$data['id']) -> delete();
            	foreach ($related_articles as $k => $v){
            		$articles = explode('_yl_', $v);
            		$related_articles_arr[$k]['id'] = $data['id'];
            		$related_articles_arr[$k]['siteid'] = $sid;
					$related_articles_arr[$k]['rid'] = $articles[0];
					$related_articles_arr[$k]['rtitle'] = $articles[1];
					$related_articles_arr[$k]['rcid'] = $articles[2];
            	}
            	if (!empty($related_articles_arr)) {
            		M('cms_relatedarticle') -> addAll($related_articles_arr);
            	}
                if (!empty($data['block_articles'])) {
                    $block_articles = implode(",",$data['block_articles']);
                    R('Block/createBlock', array(array($data['id']), $block_articles));
                }

                S('cache_contents_'.$data['id'], null);
            	if($data['classid'] ==="3" && $data['pic_ischange']==="Y"){
            		D('Picture') -> where("`articleid`=".$data['id']) ->delete();
            		$imageurl = $data["imageurl"];
            		$imagedes = $data["imagedes"];
            		$nowtime = time();
            		foreach ($imageurl as $k => $v){
            			$pictures[$k]["siteid"] = $data["siteid"];
            			$pictures[$k]["categoryid"] = $data["cid"];
            			$pictures[$k]["articleid"] = $data["id"];
            			$pictures[$k]["authorid"] = $this->mid;
            			$pictures[$k]["author"] = $data["author"];
            			$pictures[$k]["ctime"] = $nowtime;
            			$pictures[$k]["utime"] = $nowtime;
            			$pictures[$k]["imageurl"] = $v;
            			$pictures[$k]["des"] = $imagedes[$k];
            		}
            		D('Picture') -> addAll($pictures);
            	}

                S('catelist'.$sid,NULL);
                S('articlelist_'.$data['cid'],NULL);
                if($cmsconfig['createcontent'] == 1){
                    $this->createContentsPage($data['id'],$data['cid'],$sid);
                }

                //判断是否回收站进入
                if($pagesource=="1"){
                	$this->assign('jumpUrl',URL('cms/Article/deletecontentlist',array('cid'=>intval($data['cid']))));
                }else{
                	$this->assign('jumpUrl',URL('cms/Article/content',array('cid'=>intval($data['cid']),'sid'=>$sid)));
                }
                $this->success('操作成功',$data['jumpUrl']);
            } else {
                $this->error('操作失败');
            }
        }
    }

    /**
     * 删除文章内容，同时删除对应的内容页面
     */
    public function delArticle(){
        $ids = $_POST['ids'];
        if(empty($ids)){
            echo 0;
            exit;
        }
        $map['id'] = array('in',$ids);
        $list = M('cms_article') -> where($map) -> select();
        if(M('cms_article') -> where($map) -> setField("status",-1)){
            $site = M('cms_site') -> where("`siteid` = {$_GET['sid']}") ->find();
            $category = M('cms_category')->where("`id`= {$_GET['cid']}")->find();
            $article_path = SITE_PATH.'/'.$site['dirname'].(empty($site['dirname'])?"":"/");
            foreach ($list as $art){
                $artnaming = str_replace('{@ChannelID}',$art['cid'],$category['artnaming']);
                $artnaming = str_replace('{@ContentID}',$art['id'],$artnaming);
                $artnaming = str_replace('{@Year}',date("Y"), $artnaming);
                $artnaming = str_replace('{cateid}', $art['cid'], $artnaming);
                $artnaming = str_replace('{contentid}', $art['id'], $artnaming);
                $article_file = $article_path.$artnaming;
                if(is_file($article_file) && file_exists($article_file)){
                    unlink($article_file);
                }
                S('articlelist_'.$art['id'],NULL);
            }
            M('cms_category') -> where("`id`= {$_GET['cid']}") -> setDec('content_num',intval($_POST['cnum']));
            S('catelist'.$_GET['sid'],NULL);
            echo 1;
        } else {
            echo 0;
        }
    }

    /**
     * 清除文章内容，同时删除对应的内容页面
     */
    public function drpArticle(){
    	$ids = $_POST['ids'];
    	if(empty($ids)){
    		echo 0;
    		exit;
    	}
    	$map['id'] = array('in',$ids);
    	$picmap['articleid'] = array('in',$ids);
    	$piclist = D('Picture') -> where($picmap) ->field('imageurl') -> select();
    	if(M('cms_article') -> where($map) -> delete()){
    		if(!empty($piclist)){
	    		D('Picture') -> where($picmap) -> delete();
	    		$isopenyun = service("Xattach") -> isOpenYun();
	    		foreach ($piclist as $k => $v){
		    		if($isopenyun){
			    		service("Xattach") -> deleteUpYunFile($v['imageurl']);
			    		continue;
		    		}
		    		if (is_file($v['imageurl']) && file_exists($v['imageurl'])){
		    			unlink($v['imageurl']);
		    		}
	    		}
    		}
    		echo 1;
    	} else {
    		echo 0;
    	}
    }

    /**
     * 还原文章内容，同时再次生成页面
     */
    public function newArticle(){
    	$ids = $_POST['ids'];
    	if(empty($ids)){
    		echo 0;
    		exit;
    	}
    	$map['id'] = array('in',$ids);
    	if(M('cms_article') -> where($map) -> setField("status",0)){
    		$list = M('cms_article') -> where($map) -> find();
    		M('cms_category') -> where("`id`=".$list['cid']) -> setInc('content_num',intval(1));
    		S('catelist'.$list['siteid'],NULL);
    		$this->createContentsPage($ids,$list['cid'],$list['siteid']);
    		echo 1;
    	} else {
    		echo 0;
    	}
    }

    /**
     * 内容分类
     * M2
     */
    public function contentmodel() {
        $modellist = M('cms_class')->select();
        $this->assign('sid',$_GET['sid']);
        $this->assign('modellist',$modellist);
        $this->display();
    }

    /**
     * 添加成功后生成内容页
     * M2
     * @param $id
     */
    public function createContentsPage($id,$cateid,$sid) {
    	//OOO  add by jepin id去除重复
    	clearIds();
    	//OOO  end
    	//得到全局配置
    	$changeStyle = model('Data')->get('cmsconfig:site-'.$sid);

    	//得到站点信息
    	if (($sited = S('cache_siteid_'.$sid)) === false) {
        	$sited = M('cms_site')->where('siteid='.$sid)->find();
        	S('cache_siteid_'.$sid, $sited);
        }

        //得到此栏目信息
        if (($clist = S('cache_channel_'.$cateid)) === false) {
        	$clist = M('cms_category')
                                ->field('(case when url <> "" then url when createurl <> "" then createurl
                                        else (concat("' . $sites['domain'] . '","/",replace(catenaming,"{cateid}",id))) end) as cateurl,
                                        replace(imageurl,"@","' . $sites['domain'] . '") as imageurl,id,plistid,cname,content,keywords,
                                        description,catetemplate,arttemplate,createurl,catenaming,artnaming,pagetitle,pagedescription,
                                        inputtime,updatetime,content_num,pid')
                                ->where('siteid=' . $sid . ' and id=' . $cateid)
                                ->find();
                S('cache_channel_' . $pid, $clist);
        }
        //内容命名规则没有时，用全局配置
    	if (!$clist['artnaming']) {
            $clist['artnaming'] = $changeStyle['artnaming'];
        }

        //查询内容资料
        $list = M('cms_article')
        ->field('(case when url <> "" then url else
                                     (concat("'.$sited['domain'].'","/",replace(replace("'.$clist['artinaming'].'","{cateid}",
                                     cid),"{contentid}",id))) end) as url,replace(imageurl,"@","'.$sited['domain'].'")
                                     as imageurl,replace(big_imageurl,"@","'.$sited['domain'].'") as big_imageurl,title,subtitle,author,updatetime,inputtime,tags,
                                     url as articleUrl,source,content,summary,group_name_collection,readpoint,keywords,description,create_uid,create_uname,update_uid,
                                    update_uname,fileurl,cid,id,siteid,comment_count')
                                            ->where(array('id' => $id,'status'=>1))->find();
        //是否有外部链接，有的话，不用成
        if (empty($list['articleUrl'])) {

            //缓存内容信息
            S('cache_contents_'.$id, $list);

            //得到内容所属模板
            if ($clist['arttemplate']) {
                $clist['arttemplate'] = iconv("UTF-8","GB2312",$clist['arttemplate']);
            } else {
                $clist['arttemplate'] = iconv("UTF-8","GB2312",$changeStyle['contentTemplate']);
            }

            //得到内容生成路径
            $artnaming = str_replace('{@ChannelID}',$list['cid'],$clist['artnaming']);
            $artnaming = str_replace('{@ContentID}',$list['id'],$artnaming);
            $artnaming = str_replace('{@Year}',date("Y"), $artnaming);
            $artnaming = str_replace('{cateid}', $list['cid'], $artnaming);
            $artnaming = str_replace('{contentid}', $list['id'], $artnaming);

            //得到站点目录
            $createdir = empty($sited['dirname'])?'':$sited['dirname'].'/';
            $createdir = './'.$createdir;
            //得到站点模板目录
            $templatedir = $createdir.'templates/';

            //包含文件
            $content = taglib('YlInclude')->parse($templatedir.$clist['arttemplate'],'',$templatedir);
            $content = taglib('YlInclude')->parse('',$content,$templatedir);
            $content = taglib('YlInclude')->parse('',$content,$templatedir);

            $content = taglib('YlSite')->parse($content,$sid);
            $content = taglib('YlSearchInput')->parse($content,$sid);

            $content = taglib('YlLocation')->parse($content, $clist, $sited, $changeStyle);
            $content = taglib('YlNavigation')->parse($content,$sid,$list['cid'],$list['id'], $sited['domain'], $changeStyle);
            $content = taglib('YlChannels')->parse($content,$sid,$clist['id'],$sited['domain'],$changeStyle);
            $content = taglib('YlContents')->parse($content,$sid,$clist,$sited['domain'],$changeStyle,$list['id']);
            if(strpos($content,'{') && strpos($content,'}')) {
                preg_match_all('/\{site\.(.*?)\}/eis',$content,$out);
                for ($i=0; $i< count($out[1]); $i++) {
                    $content = str_ireplace($out[0][$i],$sited[$out[1][$i]],$content);
                }
                preg_match_all('/\{Channel\.(.*?)\}/eis',$content,$match);
                for ($i=0; $i< count($match[1]); $i++) {
                    $content = str_ireplace($match[0][$i],$clist[$match[1][$i]],$content);
                }
                preg_match_all('/\{Content\.(.*?)\}/eis',$content,$match);
                for ($i=0; $i< count($match[1]); $i++) {
                    $content = str_ireplace($match[0][$i],$list[$match[1][$i]],$content);
                }
            }
            $content = taglib('YlSqlContents')->parse($content);
            $content = taglib('YlSqlContent')->parse($content);

            $content = taglib('YlBlock')->parse($content,$sid,$sited['domain'],$changeStyle);
            $content = taglib('YlComments')->parse($content,$list['id']);
            $content = taglib('YlA')->parse($content,$sid,$list,'1',$sited['domain'],$changeStyle);
            $content = taglib('YlImage')->parse($content,$list);

            $content = taglib('YlIf')->parse($content, $list);

            $content = taglib('YlContent')->parse($content,$list,$sited['domain']);
            $content = taglib('YlChannel')->parse($content,$clist,$sid,$sited['domain'],$changeStyle);

            $content = taglib('YlAd')->parse($content, $sid);
            $content = taglib('YlCount')->parse($content,$list);
//            $content = taglib('YlUrl')->parse($content);
            if(dirname($createdir.$artnaming))
                mk_dir(dirname($createdir.$artnaming));
            file_put_contents($createdir.$artnaming,$content);
            //OOO  add by jepin id去除重复
            clearIds();
            //OOO  end
        }
    }

    public function getArticleList() {
        if($_POST) {
            $id = intval($_POST['id']);
            echo D('Article')->getArticleList($id);
        }
    }

    /**
     * 内容分类状态设置
     */
    public function setClassStatus(){
        $id = $_GET['id'];
        $status = $_GET['status'];
        if(M('cms_class') -> where("`id` = {$id}") -> setField('status',$status)){
            $sid = $_GET['sid'];
            S('modellist'.$sid,null);
            $this->assign('jumpUrl', URL('cms/Article/contentmodel'));
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }

    /**
     * 修改内容分类模板
     */
    public function updateClass(){
        $id = $_GET['id'];
        $class = M('cms_class') -> where("`id` = {$id}") ->find();
        $type = $_GET['class_alia_name'];
        $fileName = "addcontent";
        if($type == "pic" || $type == "3"){
            $fileName = "addpic_content";
        } else if ($type == "video" || $type == "2"){
            $fileName = "addvideo_content";
        }

        $filepath = SITE_PATH."/apps/cms/Tpl/Article/".$fileName.".html";
        if(file_exists($filepath)) {
            $content = file_get_contents($filepath);
        }
        $content = htmlspecialchars($content, ENT_NOQUOTES, 'UTF-8');
        $class['templatePath'] = $filepath;
        $class['templateContent'] = $content;
        $class['templateName'] = $fileName;
        $this->assign("class",$class);
        $this->display();
    }

    /**
     * 执行修改内容分类模板
     */
    public function doupdateClass(){
        if($_POST) {
            $data = $_POST;
            $templateContent = $data['templateContent'];
            $templateName = $data['templateName'];
            $name_arr = array('addcontent','addpic_content','addvideo_content');

            if(in_array($templateName,$name_arr) === false){
                $this->error('操作失败'.$templatePath);
                exit();
            }
            $templatePath = SITE_PATH."/apps/cms/Tpl/Article/".$templateName.".html";
            $content = stripslashes($templateContent);
            $content = str_replace("<br />"," ",$content);
            unlink($templatePath);
            if(file_put_contents($templatePath,$content) === false){
                $this->error('操作失败'.$templatePath);
            } else {
                $this->assign('jumpUrl',URL('cms/Article/contentmodel'));
                $this->success('操作成功');
            }
        }
    }

    /**
     * 得到指定站点栏目列表
     * sun
     */
    private function getSiteCateBySid($sid,$cid) {
    	if(($string = S('cache_sitecate_tree_siteid_'.$sid.'_cid_'.$cid)) === false ){
    		if (($sited = S('cache_siteid_'.$sid)) === false) {
    			$sited = M('cms_site')->where('siteid='.$sid)->find();
    			S('cache_siteid_'.$sid, $sited);
    		}
    		$list = D('Category')->channelAllList($sited['siteid'],$sited['name']);
    		$string = "<select id='cid' name='cid'>";
    		$string .= "<option value='0'>全部</option>";
    		$str = "<option \$selected value='\$id'>\$spacer \$cname </option>;";
    		import('Tree');
    		$tree = new Tree();
    		$tree->init($list);
    		$string .= $tree->get_tree_category(0, $str,'',$cid);
    		$string .= "</select>";
    		if(!empty($list)){
    			S('cache_sitecate_tree_siteid_'.$sid.'_cid_'.$cid, $string);
    		}
    	}
    	$this->assign('alist',$string);
    }

    /**
     * 得到栏目列表
     * next
     */
    private function getSiteCate($cid) {
    	$siteid="";
    	$sitename="";
    	//得到内容列表的权限
    	$rid = M('role_user') -> where("user_id =".$_SESSION['mid']) -> field("role_id") -> find();
    	if($rid){
    		$sids = M('access') ->join(" as a left join ".C ( 'DB_PREFIX' ) ."node as n on a.node_id = n.id")
    		-> where(" a.role_id=".$rid["role_id"]." and a.level=3 and n.name='contentlist'") -> field("n.sid") -> select();
    	}
    	if(empty($sids)){
    		$sitelist = M('cms_site')->order('siteid asc')->select();
    	}else{
    		foreach ($sids as $k => $v){
    			$sids[$k] = $v['sid'];
    		}
    		$map['siteid'] = array('in',implode(",",$sids));
    		$sitelist = M('cms_site')->where($map)->order('siteid asc')->select();
    	}
    	if(!empty($sitelist)){
    		foreach ($sitelist as $k => $v) {
    			$siteid=$siteid.','.$v['siteid'];
    			$sitename=$sitename.','.$v['name'];
    		}
    	}
    	//去掉最前面的,
    	if(!empty($siteid)){
    		$siteid=substr($siteid,1);
    		$sitename=substr($sitename,1);
    	}
    	$list = D('Category')->channelAllList($siteid,$sitename);
    	$string = "<select id='cid' name='cid'>";
    	$string .= "<option value='0'>全部</option>";
    	$str = "<option \$selected value='\$id'>\$spacer \$cname </option>;";
    	import('Tree');
    	$tree = new Tree();
    	$tree->init($list);
    	$string .= $tree->get_tree_category(0, $str,'',$cid);
    	$string .= "</select>";
    	$this->assign('alist',$string);
    }

    /**
     * 将全站栏目列表封装成tree
     * M2
     */
    public function cateTreeAllList() {
    	$siteid="";
    	$sitename="";
    	//得到内容列表的权限
    	$rid = M('role_user') -> where("user_id =".$_SESSION['mid']) -> field("role_id") -> find();
    	if($rid){
    		$sids = M('access') ->join(" as a left join ".C ( 'DB_PREFIX' ) ."node as n on a.node_id = n.id")
    		-> where(" a.role_id=".$rid["role_id"]." and a.level=3 and n.name='contentlist'") -> field("n.sid") -> select();
    	}
    	if(empty($sids)){
    		$sitelist = M('cms_site')->order('siteid asc')->select();
    	}else{
    		foreach ($sids as $k => $v){
    			$sids[$k] = $v['sid'];
    		}
    		$map['siteid'] = array('in',implode(",",$sids));
    		$sitelist = M('cms_site')->where($map)->order('siteid asc')->select();
    	}
    	//得到站点列表
    	foreach ($sitelist as $k => $v) {
    		$siteid=$siteid.','.$v['siteid'];
    		$sitename=$sitename.','.$v['name'];
    	}
    	//去掉最前面的,
    	if(!empty($siteid)){
    		$siteid=substr($siteid,1);
    		$sitename=substr($sitename,1);
    	}
    	echo D('Category')->getCateAllList($siteid,$sitename);
    }

    /**
     * 将全站栏目列表封装成tree
     * yan
     */
    public function cates() {
        $siteid="";
        $sitename="";
        //得到内容列表的权限
        $rid = M('role_user') -> where("user_id =".$_SESSION['mid']) -> field("role_id") -> find();
        if($rid){
            $sids = M('access') ->join(" as a left join ".C ( 'DB_PREFIX' ) ."node as n on a.node_id = n.id")
            -> where(" a.role_id=".$rid["role_id"]." and a.level=3 and n.name='contentlist'") -> field("n.sid") -> select();
        }
        if(empty($sids)){
            $sitelist = M('cms_site')->order('siteid asc')->select();
        }else{
            foreach ($sids as $k => $v){
                $sids[$k] = $v['sid'];
            }
            $map['siteid'] = array('in',implode(",",$sids));
            $sitelist = M('cms_site')->where($map)->order('siteid asc')->select();
        }
        //得到站点列表
        foreach ($sitelist as $k => $v) {
            $siteid=$siteid.','.$v['siteid'];
            $sitename=$sitename.','.$v['name'];
        }
        //去掉最前面的,
        if(!empty($siteid)){
            $siteid=substr($siteid,1);
            $sitename=substr($sitename,1);
        }
        echo D('Category')->getAllCates($siteid,$sitename);
    }

    /*
     * 审核和生成
     * M2
     */
    public function oper() {
        $ids = $_REQUEST['ids'];
        if(empty($ids)){
            echo 0;
            exit;
        }

        if ($_REQUEST['type'] === 'sh') {
            $map['status'] = 1;
            if (M('cms_article') -> where(array('id' => array('in', $ids))) -> save($map)) {
                echo 1;
            } else {
                echo 0;
            }
        } elseif ($_REQUEST['type'] === 'publish') {
            $list = M('cms_article')->where(array('id' => array('in', $ids)))->select();
            foreach ($list as $k => $v) {
                $this->createContentsPage($v['id'], $v['cid'], $v['siteid']);
            }
            echo 1;
        }

    }


    /**
     * 获取图片真实路径
     * @param unknown_type $str_domain 当前站点id
     * @param unknown_type $str_imageurl 需处理图片url
     */
    private function getRealImageUrl($str_domain,$str_imageurl){
    	if (($sited = S('cache_siteid_1_domain')) === false) {
    		$domain = M('cms_site') ->where("siteid = 1") -> getField("domain");
    		S('cache_siteid_1_domain', $domain);
    	}
    	if(strpos($str_imageurl,"@") ===0){
    		$str_imageurl = $str_domain.substr($str_imageurl,1);
    	}elseif (strpos($str_imageurl,"/") ===0){
    		if(strpos($str_imageurl,__ROOT__."/") ===0)
    			return $str_imageurl;
    		$str_imageurl = $str_domain.$str_imageurl;
    	}elseif (strpos($v['imageurl'],"~") ===0){
    		$str_imageurl = $domain.$str_imageurl;
    	}
    	return $str_imageurl;
    }

    /**
     * 文章预览
     */
    public function preview(){
    	if($_GET['id']){
    		if (($art = S('cache_contents_'.$_GET['id'])) === false) {
    			$art = M('cms_article')->where("`id`=".intval($_GET['id']))->find();
    			S('cache_contents_'.$_GET['id'], $art);
    		}
    		if (($sited = S('cache_siteid_'.$art['siteid'])) === false) {
    			$sited = M('cms_site')->where('siteid='.$art['siteid'])->find();
    			S('cache_siteid_'.$art['siteid'], $sited);
    		}
    		if(empty($art['url'])){
    			// 获取站点目录
    			$dirname = $sited['dirname'];
    			// 获取内容的命名规则
    			if ($category_list = S('cache_channel_'.$art['cid']) === false) {
    				$category_list = M('cms_category')->where('id='.$art['cid'])->find();
    				S('cache_channel_'.$art['cid'], $category_list);
    			}
    			$artnaming = $category_list['artnaming'];
    			if (empty($artnaming)) {
    				$changeStyle = model('Data')->get('cmsconfig:site-'.$art['siteid']);
    				$artnaming = $changeStyle['artnaming'];
    			}
    			$artnaming = str_replace('{@ChannelID}', $art['cid'], $artnaming);
    			$artnaming = str_replace('{@ContentID}', $art['id'], $artnaming);
    			$artnaming = str_replace('{@Year}', date("Y"), $artnaming);
    			$artnaming = str_replace('{cateid}', $art['cid'], $artnaming);
    			$artnaming = str_replace('{contentid}', $art['id'], $artnaming);
    			$arturl=$dirname . '/'. $artnaming;
    		}else{
    			$arturl =$art['url'];
    		}
    		echo  '<script>location.href="'.$arturl.'"</script>';
    	}
    }

    /* 根据内容ID删除所属区块
     * M2
     * @param int $contentID
     * @return 1
     */
    public function delBlockByContentID() {
        $id = $_POST['id'];
        $contentID = $_POST['contentID'];

        if (D('Block')->delBlockListByContentID($id, $contentID)) {
            echo '1';
        } else {
            echo '0';
        }
    }
}
?>
